package com.campus.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.app.mapper.CloudFileMapper;
import com.campus.app.service.CloudFilesService;
import com.campus.commons.entity.CloudFile;
import com.campus.commons.utils.Result;
import com.campus.commons.utils.oss.AliOssCloudUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Min;
import java.util.List;

@Service
public class CloudFilesServiceImpl extends ServiceImpl<CloudFileMapper, CloudFile> implements CloudFilesService {
    @Autowired
    private CloudFileMapper cloudFileMapper;
    @Autowired
    private DepartmentsServiceImpl departmentsService;

    @Override
    public Result<List<CloudFile>> getFile(int page, int limit, @Min(1) int fileDeId) {
        Result<List<CloudFile>> result = new Result<>();
        QueryWrapper<CloudFile> queryWrapper = new QueryWrapper<>();
        List<CloudFile> file = cloudFileMapper.getFile((page - 1) * limit, limit, fileDeId);
        Integer count = 0;
        if (file.size() != 0) {
            queryWrapper.eq("filedeId", fileDeId);
            count = cloudFileMapper.selectCount(queryWrapper);
        }
        result.setData(file);
        result.setTotal(count);
        result.setSuccess(true);

        return result;
    }

    @Override
    public Result delFileById(@Min(1) int fileId, String filePath) {
        int i = cloudFileMapper.deleteById(fileId);
        if (i == 1) {
            //如果数据库删除成功删除云存储的文件
            DelOss(filePath);
        }
        return Result.result(i);
    }

    @Override
    public Result<List<CloudFile>> getAllByTime(int page, int limit, String time, int deId) {
        Result<List<CloudFile>> result = new Result<>();
        QueryWrapper<CloudFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("upTime", time);
        List<CloudFile> buyFile = cloudFileMapper.getFileByTime((page - 1) * limit, limit, time, deId);
        int count = 0;
        if (buyFile.size() != 0) {
            count = cloudFileMapper.selectCount(queryWrapper);
        }
        result.setSuccess(true);
        result.setTotal(count);
        result.setData(buyFile);
        return result;
    }

    @Async
    public void DelOss(String filePath) {
        AliOssCloudUtil.deleteFile(filePath);
    }
}
